 //
//  HotCarTableViewController.m
//  CarWorld
//
//  Created by yuyu on 15/3/25.
//  Copyright (c) 2015年 CarWorldTeam. All rights reserved.
//

#import "HotCarTableViewController.h"
#import "y_HotCarTableViewCell.h"
#import "JSONKit.h"
#import "y_HotCarCellData.h"
#import "HotCarDetailViewController.h"


#define CELLHEIGHT 65
@interface HotCarTableViewController ()
@property(nonatomic,retain)NSMutableArray *hotArray;
@property(nonatomic,retain)NSArray *headTitleArray;
@property(nonatomic,retain)UIActivityIndicatorView *activityIndicator;
@property(nonatomic,retain)NSOperationQueue *queue;
@end

@implementation HotCarTableViewController

- (void)dealloc
{
    [_hotArray release];
    [_headTitleArray release];
    [_activityIndicator release];
    [_queue release];
    [super dealloc];
}
#pragma mark - 同步下载文字信息，卡，但是界面出来的快
- (void)getHotInfoFromNetSynchronous
{
    [self addJuHua];
    NSURL *url = [NSURL URLWithString:@"http://db.auto.sohu.com/epicjson/hotmodel.sip"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    if (data) {
        [self parisData:data];
        }
    [self stopAnimating];
}
#pragma mark - 异步下载文字信息，不卡，界面出来的比较慢
- (void)getHotInfoFromNetAsynchronous
{
    [self addJuHua];
    NSURL *url = [NSURL URLWithString:@"http://db.auto.sohu.com/epicjson/hotmodel.sip"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[[[NSOperationQueue alloc] init] autorelease] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            [self parisData:data];
        }
    }];
}

- (void)getHotInfoFromFile
{
    [self addJuHua];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"hotCar" ofType:@"txt"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    self.hotArray = [NSMutableArray array];
    NSDictionary *dic1 = dic[@"RESULT"];
    for (NSString *key in dic1) {
        NSMutableArray *sectionArr = [NSMutableArray array];
        NSArray *arr = dic1[key];
        for (NSDictionary *dic2 in arr) {
            y_HotCarCellData *cellData = [[y_HotCarCellData alloc] init];
            [cellData setValuesForKeysWithDictionary:dic2];
            [sectionArr addObject:cellData];
            [cellData release];
        }
        [_hotArray addObject:sectionArr];
    }
    [self stopAnimating];
}

- (void)parisData:(NSData *)data
{
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
    NSString *dicString = [[NSString alloc]initWithData:data encoding:enc];
    NSData *pdata =  [dicString dataUsingEncoding:NSUTF8StringEncoding];
    if (pdata) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:pdata options:NSJSONReadingMutableLeaves|NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic1 = dic[@"RESULT"];
        for (NSString *key in dic1) {
            NSMutableArray *sectionArr = [NSMutableArray array];
            NSArray *arr = dic1[key];
            for (NSDictionary *dic2 in arr) {
                y_HotCarCellData *cellData = [[y_HotCarCellData alloc] init];
                [cellData setValuesForKeysWithDictionary:dic2];
                [sectionArr addObject:cellData];
                [cellData release];
            }
            [_hotArray addObject:sectionArr];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [self stopAnimating];
        });
    }
}

- (void)addJuHua
{
    self.activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
    
    CGFloat pX = [UIScreen mainScreen].bounds.size.width/2-50;
    _activityIndicator.frame = CGRectMake(pX, 100, 100, 50);
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 100, 20)];
    lbl.text = @"正在加载...";
    lbl.font = [UIFont systemFontOfSize:10];
    lbl.textAlignment = NSTextAlignmentCenter;
    [_activityIndicator addSubview:lbl];
    [lbl release];
    [_activityIndicator startAnimating];
    [self.view addSubview:_activityIndicator];
    self.view.userInteractionEnabled = NO;
}

- (void)stopAnimating
{
    [_activityIndicator stopAnimating];
    self.view.userInteractionEnabled = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"热门车型";
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:41/255.0 green:129/255.0 blue:255/255.0 alpha:1];
    //[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.hotArray = [NSMutableArray array];
    self.headTitleArray = [NSArray arrayWithObjects:@"小型车",@"紧凑型车",@"中型车",@"SUV",@"MPV", nil];
    
    [self getHotInfoFromNetAsynchronous];//runloop找资料看看
    
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return _hotArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [_hotArray[section] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuseIdentifier = @"hotCar";
    y_HotCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell==nil) {
        cell = [[y_HotCarTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier height:CELLHEIGHT];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        //        //取消选中颜色
        //        UIView *backView = [[UIView alloc] initWithFrame:cell.frame];
        //        backView.backgroundColor = [UIColor clearColor];
        //        cell.selectedBackgroundView = backView;
        //        [backView release];
    }
    y_HotCarCellData *cellData = _hotArray[indexPath.section][indexPath.row];
    if (cellData.image==nil) {
        [cellData addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew context:[indexPath retain]];
    }

    cell.cellData = cellData;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELLHEIGHT;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSIndexPath *indexPath = (NSIndexPath *)context;
    NSArray *array = [self.tableView indexPathsForVisibleRows];
    if ([array containsObject:indexPath]) {
        y_HotCarTableViewCell *cell = (y_HotCarTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
        UIImage *image = (UIImage *)[change objectForKey:@"new"];
        cell.image_View.image = image;
        //[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
    [indexPath release];
}

//- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section
//{
//    tableView.tableHeaderView = view;
//}

//- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return YES;
//}

//- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section
//{
// fafafjlajfljwowodeweilaibushimeng
//}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[[UIView alloc] init] autorelease];
    float fcolor = 0.95;
    view.backgroundColor = [UIColor colorWithRed:fcolor green:fcolor blue:fcolor alpha:1.0];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 100, 10)];
    titleLabel.text = _headTitleArray[section];
    titleLabel.font = [UIFont systemFontOfSize:12];
    [view addSubview:titleLabel];
    [titleLabel release];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*
     UIModalTransitionStyleCoverVertical=0, //默认方式，竖向上推
     UIModalTransitionStyleFlipHorizontal, //水平反转
     UIModalTransitionStyleCrossDissolve,//隐出隐现
     UIModalTransitionStylePartialCurl,//部分翻页效果
     */
    HotCarDetailViewController *hotTableVC = [[HotCarDetailViewController alloc] init];
    y_HotCarCellData *cellData = _hotArray[indexPath.section][indexPath.row];
    hotTableVC.mid = [cellData MODEL_ID];
    UINavigationController *hotDetailNaVc = [[UINavigationController alloc] initWithRootViewController:hotTableVC];
    [hotDetailNaVc setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self presentViewController:hotDetailNaVc animated:YES completion:^{
        
    }];
    [hotTableVC release];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
